//
//  STFeedListViewModel.swift
//  Story
//
//  Created by 汤泽川 on 2019/4/19.
//  Copyright © 2019 汤泽川. All rights reserved.
//

import Foundation
import UIKit
import RxSwift
import RxCocoa

class STFeedListViewModel {
    private let storyService = STStoryService()
    
    let data = BehaviorRelay<[STStoryInfo]>(value: [])
    let endHeaderRefreshing : Observable<Bool>
    let endFooterRefreshing : Observable<Bool>
    
    init(input: (headerRefresh: Observable<Void>, footerRefresh: Observable<Void> ), dependency: (disposeBag:DisposeBag, networkService: STStoryServiceManager )) {
        // 下拉
        let headerRefreshData = input.headerRefresh.flatMapLatest { _ in
            dependency.networkService.refresh().takeUntil(input.footerRefresh)
            }.share(replay: 1)
        // 上拉
        let footerRefreshData = input.footerRefresh.flatMapLatest { _ in
            dependency.networkService.loadMore().takeUntil(input.footerRefresh)
            }.share(replay: 1)
        //生成停止头部刷新状态序列
        self.endHeaderRefreshing = Observable.merge(
            headerRefreshData.map{ _ in true },
            input.footerRefresh.map{ _ in true }
        )
        
        //生成停止尾部刷新状态序列
        self.endFooterRefreshing = Observable.merge(
            footerRefreshData.map { infos in
                return infos.count != 0
            },
            input.headerRefresh.map{ _ in true }
        )
        
        //下拉刷新时，直接将查询到的结果替换原数据
        headerRefreshData.subscribe(onNext: { items in
            self.data.accept(items)
        }).disposed(by: dependency.disposeBag)
        
        //上拉加载时，将查询到的结果拼接到原数据底部
        footerRefreshData.subscribe(onNext: { items in
            self.data.accept(self.data.value + items )
        }).disposed(by: dependency.disposeBag)
    }
    
    func registerTableViewCell(_ tableView : UITableView) {
        tableView.register(STFeedListStoryCell.self, forCellReuseIdentifier: "\(STFeedListStoryCell.self)")
        tableView.register(STFeedListStoryWithImageCell.self, forCellReuseIdentifier: "\(STFeedListStoryWithImageCell.self)")
    }
}
